package com.com.typhoon.config;

import com.com.typhoon.entity.Permission;
import com.com.typhoon.entity.Role;
import com.com.typhoon.entity.User;
import com.com.typhoon.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author shuya | dongfeng.zdf@alibaba-inc.com
 * @description
 * @date 2018/10/29 下午10:07
 * @description
 * @modified by
 * @since V2.0.0
 */
@Slf4j
public class CustomAuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User)principalCollection.getPrimaryPrincipal();
        Collection<Role> roleList = user.getRoles();
        List<Long> roleIds = new ArrayList<>();
        for (Role role: roleList) {
            simpleAuthorizationInfo.addRole(role.getName());
            roleIds.add(role.getId());
        }
        List<Permission> permissionList =  this.userService.queryPermissionByRoles(roleIds);
        for(Permission permission : permissionList) {
            simpleAuthorizationInfo.addStringPermission(permission.getName());
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证(登录)
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        // 获取登录的用户名
        String userName = usernamePasswordToken.getUsername();
        // 从数据库中查询用户
        User user = userService.findByUsername(userName);
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
    }
}
